package nonre.sgy.gencode.gen;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class GenUtil {

	public static Template getTemplate(String path){
		return Velocity.getTemplate(path,"utf-8");
	}
	
	
	public static void genFile(Template template, VelocityContext context, File file) throws Exception {
		genFile(template, context, file, false);
	}

	public static void genFile(Template template, VelocityContext context, File file, boolean overwrite)
			throws Exception {
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		if ((!file.exists()) || (overwrite)) {
			FileOutputStream fos = new FileOutputStream(file);
			PrintWriter writer = new PrintWriter(new java.io.OutputStreamWriter(fos, "utf-8"), true);
			template.merge(context, writer);
			writer.close();
		}
	}
	
	public static String toCamelString(String name){
		return name.substring(0, 1).toLowerCase() + name.substring(1);
	}
	
	/**
	 * 获取类及其父类的所有声明的属性
	 * 如果属性既final又是static的，会先判断final
	 * 
	 * @param clazz
	 * @param getStatic 是否获取static的属性
	 * @param getFinal  是否获取final的属性
	 * @return 属性列表
	 */
	public static List<Field> getFields(Class<?> clazz,boolean getStatic,boolean getFinal) {
		List<Field> fieldList = new ArrayList<Field>();
		while (clazz != null) {
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
//				System.out.print(field.getName()+" ");;
//				System.out.println(field.getModifiers());;
//				System.out.println(Modifier.isFinal(field.getModifiers()));
//				System.out.println(Modifier.isStatic(field.getModifiers()));
				
				if (Modifier.isFinal(field.getModifiers())) {
					if (getFinal) {
						fieldList.add(field);
					}
				}else if (Modifier.isStatic(field.getModifiers())) {
					if (getStatic) {
						fieldList.add(field);
					}
				}else {
					fieldList.add(field);
				}
				
				
				
			}
			clazz = clazz.getSuperclass();
		}
//		java.util.Collections.reverse(fieldList);
		return fieldList;
	}
	
	/**
	 * 获取类及其父类的所有声明的属性
	 * @param clazz
	 * @return 属性列表
	 */
	public static List<Field> getFields(Class<?> clazz) {
		return getFields(clazz, false, false);
	}
	
	public static void main(String[] args) {
		System.out.println(toCamelString("AAA"));
	}
	
}
